/*
 * @Author: lusx 
 * @Date: 2020-05-02 20:24:21 
 * @Last Modified by: lusx
 * @Last Modified time: 2020-05-21 11:40:55
 */
import { observable, action, computed, toJS } from 'mobx';
import { Form, ListPage } from "weaver-mobile-page";
import { Bubble } from 'weaver-mobile';
import Validator from 'validatorjs/dist/validator.min.js';
import { cloneDeep, mapKeys } from 'lodash';
import { governSetupInit, saveAdd } from "../../apis/govern";
export default class AddStore {
    @observable projectForm = new Form.Store({ route: "/quickbar/add" });
    @observable taskForm = new Form.Store({ route: "/quickbar/add/task" });
    @observable loading = false;
    @observable saveloading = false;
    @observable count = 0;
    @observable taskForms = {};
    condition = {};
    categoryid = '';
    @observable canSubmit = true;
    @observable list = new ListPage.Store();
    @observable currentIndex = null;//添加时,当前的路由index
    @computed get taskFormskeys() {
        return Object.keys(this.taskForms);
    }
    @computed get data() {
        const initArr = [-999];
        const source = this.taskFormskeys.length > 0 ? Object.keys(this.taskForm.formParams).length > 0 ? [...this.taskFormskeys] : [...this.taskFormskeys] : initArr; //如果点击添加了,list的数据源便由 taskForms 决定
        const data = source.map((theme, i) => ({
            title: `子任务_${i + 1}`,
            id: `id_${theme}`,
        }));
        return data;
    }

    @action
    init = (params) => {
        this.loading = true;
        this.categoryid = params.categoryid;

        governSetupInit(params).then(data => {
            if (data.status === '1') {
                this.projectForm.initForm(data.condition1, '/quickbar/add');
                // this.taskForm.initForm(data.condition2, '/quickbar/add/task');
                this.condition = cloneDeep(data.condition2);
                this.count = 0;
                const condition = this.setCondition(this.taskFormskeys.length);
                this.taskForms = Object.assign({}, { [this.count]: new Form.Store({ route: `/quickbar/add/add-task/${this.count}` }) })
                this.taskForms[this.count].initForm(condition, `/quickbar/add/add-task/${this.count}`);
            }
        })
            .catch(err => { console.error(err) })
            .finally(() => { this.loading = false })
    }

    setCondition = (index) => {
        const newCondition = this.condition[0].items.map(item => {
            const domkey = `${item.domkey[0]}标${index}`;
            return { ...item, domkey: [domkey] }
        })
        return [{ title: (index).toString(), defaultshow: true, items: [...newCondition] }];
    }

    @action
    setCount = (params = {}) => {
        const { type = undefined } = params;
        if (type === 'add') {
            this.count++;
            const condition = this.setCondition(this.count);
            this.taskForms = Object.assign({ ...this.taskForms }, { [this.count]: new Form.Store({ route: `/quickbar/add/add-task/${this.count}` }) })
            // this.taskForms[this.taskFormskeys.length-1].initForm(condition, `/quickbar/add/add-task/${this.taskFormskeys.length-1}`);
            this.taskForms[this.count].initForm(condition, `/quickbar/add/add-task/${this.count}`);
        }
        else {
            const { index } = params;
            const { [index.toString()]: { }, ...others } = this.taskForms;
            this.taskForms = Object.assign({}, others);
            this.count++;
        }
    }

    @action
    save = (params) => {
        this.saveloading = true;
        return this.validatorTasks(params).then((result) => {
            if (result === true) {
                return this.saveAction();
            } else {
                this.saveloading = false;
            }
        })
    }

    @action
    saveAction = () => {
        const newParams = { categoryid: this.categoryid, ...this.preSave() };
        return saveAdd(newParams).then(data => {
            return import('../../util/tools').then(({ sleepInAsync }) => {
                if (data.status === '1') {
                    Bubble.success('保存成功', 1);
                    return sleepInAsync({ interval: 2000, params: { result: '1' } });
                } else if (data.status == -3) {
                    Bubble.error('保存失败', 0);
                    return sleepInAsync({ interval: 2000, params: { result: '-3' } });
                } else {
                    Bubble.warning('发生错误', 0);
                    return sleepInAsync({ interval: 2000, params: { result: '' } });
                }
            })

        })
            .catch(err => { console.error(err) })
            .finally(() => {
                this.count = 0;
                this.saveloading = false;
            })
    }

    @action
    preSave = () => {
        let projectParams = this.projectForm.formParams;
        const taskParams = this.taskForm.formParams;
        let newTaskParams = [];
        const length = this.taskFormskeys.length;
        for (let i = 0; i < length; i++) {
            const currentTaskParams = this.setFormParams(this.taskForms[this.taskFormskeys[i]].formParams,`标${i}`);
            newTaskParams.push({ ...currentTaskParams });
        }
        const tasks = Object.keys(taskParams).length > 0 ? JSON.stringify([{ ...taskParams }].concat(newTaskParams)) : JSON.stringify(newTaskParams);
        const params = { 'tasks': tasks, ...projectParams };
        return params;
    }

    // insertRemark =(remarkdata,index,formParam) =>{
    //     if(index<0&&remarkdata['remark']){
    //         formParam.remark = remarkdata['remark'];
    //         console.log('res',formParam)
    //     }
    //     if(index>=0&&remarkdata[`remark标${index}`]){
    //         formParam.remark = remarkdata[`remark标${index}`]
    //         console.log('res',formParam)
    //     }
    //     return formParam;
    // }

    @action
    validator = (params) => {
        const { pathname, item,formname } = params;
        return import('../../util/tools').then(({ validatorTool }) => {
            if (pathname.endsWith('add')) {
                return validatorTool(this.projectForm);
            } else if (pathname.endsWith('task')) {
                return validatorTool(this.taskForm);
            } else if (pathname.includes('add-task')) {
                const current = pathname.split('/').pop();
                return validatorTool(this.taskForms[current]);
            } else if (pathname.includes('/add/list')) {
                return validatorTool(this.taskForms[item],formname);
            }
            else {
                return true;
            }
        })
    }

    @action
    validatorTasks = (params) => {
        const { pathname } = params;
        const source = [...this.taskFormskeys];
        if (source.length == 0) {
            return Promise.resolve(true);
        }
        let _this = this;
        return new Promise(function (resolve, reject) {
            source.map((item, index) => {
                let formname = `子任务_${index + 1}`;
                _this.validator({ pathname, item,formname}).then((result) => {
                    if (result === false) {
                        resolve(false);
                    }
                    if (index == source.length - 1) {
                        resolve(true);
                    }
                })
            })
        })
    }

    @action
    currentIndexFun = (params = { currentIndex: null }) => {
        this.currentIndex = params.currentIndex;
    }

    // *******************工具函数***********************
    canSubmitFun = (params = { canSubmit: false }) => {
        this.canSubmit = params.canSubmit;
    }
    setFormParams = (formParams,replaceStr) => {
        const go = Object.keys(formParams)[0].includes('标');
        if (go === true) {
            const newFormParams = mapKeys(formParams, (value, key) => {
                const newKey = key.replace(replaceStr,'');
                return newKey;
            })
            return newFormParams;
        } else {
            return formParams;
        }
    }
    // *************************************************
}